package jeumpapayment.record;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

public class UserData {
	private String phonenumber;
	private String password;
	private String email;
	
	public UserData(){
		phonenumber = null;
		password = null;
		email = null;
	}
	
	public void loadRecord() throws RecordStoreFullException, RecordStoreNotFoundException, RecordStoreException, IOException{
		RecordStore rs = RecordStore.openRecordStore("userdata", true);
		 
		if(rs.getNumRecords() == 0){
			rs.closeRecordStore();
			return;
		}
		
		// Create input stream
		ByteArrayInputStream bais = new ByteArrayInputStream(rs.getRecord(1));
		DataInputStream dis = new DataInputStream(bais);
		
		// Read data
		phonenumber = dis.readUTF();
		password = dis.readUTF();
		email = dis.readUTF();
		
		// Close stream & connection
		dis.close();
		bais.close();
		rs.closeRecordStore();
	}
	
	public void saveRecord() throws RecordStoreFullException, RecordStoreNotFoundException, RecordStoreException, IOException{
		if(phonenumber==null || password==null || email==null) return;
		
		RecordStore rs = RecordStore.openRecordStore("userdata", true);
		if(rs.getNumRecords() != 0) rs.deleteRecord(1);
				
		// Create output stream
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		
		// Write data to buffer
		dos.writeUTF(phonenumber);
		dos.writeUTF(password);
		dos.writeUTF(email);
		dos.flush();
		
		// Write to record store
		rs.addRecord(baos.toByteArray(), 0, baos.toByteArray().length);
		
		// Close stream & connection
		dos.close();
		baos.close();
		rs.closeRecordStore();
	}
	
	public String getPhonenumber() {
		return phonenumber;
	}

	public void setPhonenumber(String phonenumber) {
		this.phonenumber = phonenumber;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}
